/*
 * *
 *  * Created with IntelliJ RustRover.
 *  * Description:
 *  * Copyright Author: ZhenYi
 *  * DateTime: 2024/2/15 下午6:22
 *
 */
use salvo::prelude::*;
use sea_orm::{DatabaseConnection, DbBackend, FromQueryResult, JsonValue, Statement};
use serde::{Deserialize, Serialize};


#[derive(Deserialize,Serialize)]
pub struct MaunNumsInput{
    state: String,
}

#[handler]
pub async fn get_maun_nums(req: &mut Request, depot: &mut Depot, res: &mut Response) {
    let input = match req.parse_json::<MaunNumsInput>().await{
        Ok(input) => input,
        Err(e) => {
            res.status_code(StatusCode::IM_USED).render(e.to_string());
            return;
        }
    };
    let input = match input.state.parse::<i32>(){
        Ok(state) => state,
        Err(e) => {
            res.status_code(StatusCode::IM_USED).render(e.to_string());
            return;
        }
    };
    let db = depot.obtain::<DatabaseConnection>().unwrap();
    if input > 11 || input < -1 {
        res.status_code(StatusCode::IM_USED).render("{\"Error\":\"State should limit 1 ~ 11\"}");
    }
    if input == -1 {
        let unique: Vec<JsonValue> = JsonValue::find_by_statement(Statement::from_sql_and_values(
            DbBackend::Postgres,
            r#" select count(*) from maunlist;"#,
            [],
        ))
            .all(db)
            .await.unwrap();
        res.status_code(StatusCode::ACCEPTED).render(
            &unique[0]
                .as_object()
                .unwrap()
                .get("count")
                .unwrap()
                .as_number()
                .unwrap()
                .as_i64()
                .unwrap()
                .to_string()
        );
        return;
    }else {
        let sql = format!("select count(*) from maunlist where stage = {};",input);
        let unique: Vec<JsonValue> = JsonValue::find_by_statement(Statement::from_sql_and_values(
            DbBackend::Postgres,
            sql,
            [],
        ))
            .all(db)
            .await.unwrap();
        res.status_code(StatusCode::ACCEPTED).render(
            &unique[0]
                .as_object()
                .unwrap()
                .get("count")
                .unwrap()
                .as_number()
                .unwrap()
                .as_i64()
                .unwrap()
                .to_string()
        );
        return;
    }
}